import React from 'react'
import { connect } from 'react-redux'
import config from 'config'
import { Form, Modal, Radio, Divider, Icon, Input, message, Button } from 'antd'
import { messages } from 'share/common'
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const FormItem = Form.Item;
import mainService from 'containers/main.service';
import ImageUpload from 'components/image-upload';
import CanvesEdit from 'containers/feedback/canvas-edit';
import EditNoSelectImg from 'images/edit-no-selected.png'
import 'styles/feedback/feedback.scss'

import feedbackService from 'containers/feedback/feedback.service'

class Feedback extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      submitLoading: false,
      moduleList: [],
      tagList: [],
      channelList: [],
      canvasVisible: false,
      successVisible: false, //提交成功弹框是否显示
      uploadType: window.ISIE9 ? 'images' : 'screen',
      imageUploadList: [],
      pictureUrls: [], //上传图片的url
      editScreenUrl: '',
    }
  }

  componentDidMount() {
    this.getList()
  }

  getList = () => {
    let params = {
      codes: ['MODULE', 'TAG', 'CHANNEL'],
      language: this.props.language.code
    };
    this.setState({ loading: true });
    feedbackService.getIssueItems(params).then(res => {
      this.setState({
        loading: false,
        moduleList: res.data.MODULE,
        tagList: res.data.TAG,
        channelList: res.data.CHANNEL
      })
    })
  };

  handleOk = () => {
    let field = this.props.form.getFieldsValue();
    const { uploadType, pictureUrls } = this.state;
    if (uploadType === 'screen') {
      let arr = (this.state.editScreenUrl || this.props.screenUrl).split(',');
      let params = {
        fileName: 'screen.jpeg',
        dataUrl: arr[1]
      };
      this.setState({ submitLoading: true });
      feedbackService.uploadImage(params).then(res => {
        this.setState({ pictureUrls: [res.data.fileURL] }, () => {
          this.handleFeedback()
        })
      }).catch(() => {
        this.setState({ submitLoading: false })
      })
    } else if (!field.issueContent && (uploadType === 'none' || !pictureUrls.length)) {
      message.warning(messages('feedback.key4'/*问题描述和图片描述请至少填写一项*/));
    } else {
      this.handleFeedback()
    }
  };


  handleFeedback = () => {
    let field = this.props.form.getFieldsValue();
    const { uploadType, pictureUrls } = this.state;
    let params = {
      modules: field.modules ? [{id: field.modules}] : [],
      tags: field.tags ? [{id: field.tags}] : [],
      issueContent: field.issueContent,
      pictureUrls: uploadType === 'none' ? [] : pictureUrls
    };
    this.state.channelList.map(item => {
      item.code === 'WY' && (params.clients = [{id: item.id}]) //WY: 网页
    });
    this.setState({ submitLoading: true });
    feedbackService.createFeedback(params).then((res) => {
      if(res.data.jump){
        //跳转客服弹窗
        mainService.udeskSignature(this.props.user, "2")
          .then((res) => {
            window.open(res.data._url);
          })
      }
      this.setState({ submitLoading: false, successVisible: true });
      Modal.success({
        title: messages('feedback.key5'/*提交成功*/),
        content: messages('feedback.key6'/*感谢您的反馈我们将尽快处理*/),
        onOk: this.props.onClose
      });
    }).catch(() => {
      this.setState({ submitLoading: false })
    })
  };

  handleCancel = () => {
    !this.state.submitLoading && this.props.onClose()
  };

  //编辑网页截图
  handleEditScreen = (url) => {
    this.setState({
      canvasVisible: false,
      editScreenUrl: url
    })
  };

  //上传图片
  handleImageUpload = (value) => {
    let pictureUrls = [];
    value.map(item => {
      pictureUrls.push(item.fileURL)
    });
    this.setState({
      imageUploadList: value,
      pictureUrls
    })
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { screenUrl } = this.props;
    const { loading, submitLoading, moduleList, tagList, canvasVisible, successVisible, uploadType, imageUploadList, editScreenUrl } = this.state;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18, offset: 1 },
    };
    return (
      <div className='feedback'>
        <div className="feedback-modal-container"/>
        <Modal title={messages('feedback.key7'/*问题反馈*/)}
               visible={!(canvasVisible || successVisible)}
               width={800}
               bodyStyle={{maxHeight: 'calc(100vh - 150px)', overflow: 'auto'}}
               getContainer={() => document.getElementsByClassName('feedback-modal-container')[0]}
               footer={(
                 <div>
                   <Button onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>
                   <Button loading={submitLoading} type="primary" onClick={this.handleOk}>{messages('common.ok')/*确定*/}</Button>
                 </div>
               )}
               onCancel={this.handleCancel}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages('feedback.key8'/*问题发生模块*/)}>
              {getFieldDecorator('modules')(
                loading ? <Icon type="loading"/> : (
                  <RadioGroup>
                    {moduleList.map(item => (
                      <Radio value={item.id} key={item.id}>{item.name}</Radio>
                    ))}
                  </RadioGroup>
                )
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('feedback.key9'/*问题类型*/)}>
              {getFieldDecorator('tags')(
                loading ? <Icon type="loading"/> : (
                  <RadioGroup>
                    {tagList.map(item => (
                      <Radio value={item.id} key={item.id}>{item.name}</Radio>
                    ))}
                  </RadioGroup>
                )
              )}
            </FormItem>
            <Divider />
            <div className="issue-submit-info">
              <Icon type="info-circle" />{messages('feedback.key4'/*问题描述和图片描述请至少填写一项*/)}
            </div>
            <FormItem {...formItemLayout} label={messages('feedback.key10'/*问题描述*/)}>
              {getFieldDecorator('issueContent')(
                <TextArea rows={3} className="issue-description-input"
                          placeholder={messages('feedback.key11'/*请描述您的问题，帮助汇联易更好的成长*/)}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('feedback.key12'/*图片描述*/)} className="image-desc-row">
              <RadioGroup value={uploadType} onChange={e => this.setState({uploadType: e.target.value})}>
                {!window.ISIE9 && <Radio value='screen'>{messages('feedback.key13'/*提交屏幕截图*/)}</Radio>}
                <Radio value='images'>{messages('feedback.key14'/*上传图片*/)}</Radio>
                <Radio value='none'>{messages('feedback.key15'/*不上传图片*/)}</Radio>
              </RadioGroup>
            </FormItem>
            {uploadType === 'screen' && (
              <FormItem {...formItemLayout} label=" " colon={false}>
                <div className="screen-container">
                  <span onClick={() => this.setState({canvasVisible: true})}><img src={EditNoSelectImg} /></span>
                  <img src={editScreenUrl || screenUrl} className="screen-img"/>
                </div>
              </FormItem>
            )}
            {uploadType === 'images' && (
              <FormItem {...formItemLayout} label=" " colon={false}>
                <div className="upload-image-notice">{messages('feedback.key16')/*图片大小不能超过3M，且只支持jpg, jpeg, bmp, gif, png格式的图片*/}</div>
                <ImageUpload uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                             attachmentType="FEEDBACK_IMAGES"
                             maxNum={9}
                             fileSize={3}
                             fileType={['jpg', 'jpeg', 'bmp', 'gif', 'png']}
                             defaultFileList={imageUploadList}
                             onChange={this.handleImageUpload}
                />
              </FormItem>
            )}
          </Form>
        </Modal>
        {canvasVisible &&  (
          <CanvesEdit imgUrl={editScreenUrl || screenUrl}
                      onOK={this.handleEditScreen}
                      onCancel={() => this.setState({canvasVisible: false})}/>
        )}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
    user: state.login.user,
  }
}

Feedback.propTypes = {
  screenUrl: React.PropTypes.string,
  onClose: React.PropTypes.func,
};

Feedback.defaultProps={
  onClose: () => {}
};

const wrappedFeedback = Form.create()(Feedback);

export default connect(mapStateToProps)(wrappedFeedback)
